<!-- 用户管理 -->
<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="关键字"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="全部" clearable class="!w-[100px]">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryParams.createTime"
            :editable="false"
            class="!w-[240px]"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button type="success" icon="plus" @click="handleOpenDialog()">新增</el-button>
          <el-button
            type="danger"
            icon="delete"
            :disabled="selectIds.length === 0"
            @click="handleDelete()"
          >
            删除
          </el-button>
        </div>
        <!-- <div>
          <el-button icon="upload" @click="handleOpenImportDialog">导入</el-button>

          <el-button icon="download" @click="handleExport">导出</el-button>
        </div> -->
      </div>

      <el-table v-loading="loading" :data="pageData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="商品名称" prop="goodsName" align="center" />
        <el-table-column label="商品标题" prop="goodsTitle" align="center" />
        <el-table-column
          label="商品编号"
          prop="goodsNo"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column label="库存" prop="stockNum" align="center" />
        <el-table-column label="活动价(元)" prop="promotionalPrice" align="center" />

        <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="150" /> -->
        <el-table-column label="操作" fixed="right" width="220" align="center">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="handleOpenDialog(scope.row.id)">
              编辑
            </el-button>
            <el-button type="success" link size="small" @click="handleImage(scope.row)">
              添加商品图片
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import GoodsAPI, { GoodsPageQuery } from "@/api/system/goods.api";

import DeptAPI from "@/api/system/dept.api";
import RoleAPI from "@/api/system/role.api";
const router = useRouter();

defineOptions({
  name: "GoodsIndex",
  inheritAttrs: false,
});
const queryFormRef = ref();
const userFormRef = ref();

const infoDialog = ref(null);
const queryParams = reactive<GoodsPageQuery>({
  page: 1,
  pageSize: 10,
});

const pageData = ref<any[]>();
const total = ref(0);
const loading = ref(false);

// 选中的用户ID
const selectIds = ref<number[]>([]);
// 部门下拉数据源
const deptOptions = ref<OptionType[]>();
// 角色下拉数据源
const roleOptions = ref<OptionType[]>();
// 导入弹窗显示状态
const importDialogVisible = ref(false);

// 查询
function handleQuery() {
  loading.value = true;
  GoodsAPI.getList(queryParams)
    .then((data) => {
      console.log(data);
      pageData.value = data;
      total.value = data.length;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.deptId = undefined;
  queryParams.createTime = undefined;
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

async function handleSuccess(value: any) {
  console.log(value);
  const { isSucceed } = await GoodsAPI.add(value);
  if (isSucceed) {
    ElMessage.success("操作成功");
    handleQuery();
  } else {
    ElMessage.error("操作失败");
  }
}
/**
 * 添加商品/编辑商品
 */
async function handleOpenDialog(id?: string) {
  router.push({ name: "AddGoods", query: { id: id } });
}

/** 添加商品图片 */
function handleImage(row?: any) {
  router.push({ name: "AddGoodsImage", query: { id: row.id, storeId: row.storeId } });
}

// 关闭弹窗
function handleCloseDialog() {
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
    }
  });
}, 1000);

/**
 * 删除商品
 *
 * @param id  用户ID
 */
function handleDelete(id?: string) {
  ElMessageBox.confirm("确认删除商品?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      GoodsAPI.deleteByIds(id)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开导入弹窗
function handleOpenImportDialog() {
  importDialogVisible.value = true;
}

onMounted(() => {
  handleQuery();
});
</script>
